import { GestureHandlerRootView } from 'react-native-gesture-handler';
import React, { useEffect, useRef } from 'react';
import BootSplash from 'react-native-bootsplash';
import { StatusBar, Platform, AppState, Appearance } from 'react-native';
import * as RNLocalize from 'react-native-localize';
import { observer } from 'mobx-react-lite';
import { useTranslation } from 'react-i18next';
import throttle from 'lodash.throttle';
import { CHECKIOSTRACKINGPERMISSION } from './utils/permission';
import { appStore, RecordKeys, Storage, deviceStore } from './store';
import AppRouter from './router';
import { Toast, BannerNotification, AgreementModal, CallNoticeModal } from './components';
import BleModule from './utils/ble/bleModule';
import QRCode from './utils/ble/qrCode';
import BleConnection from './utils/ble/connect';
import * as cmd from './utils/ble/cmd.js';
import { modelDevices } from './utils/deviceMenues';

let qrCode = new QRCode();
let BluetoothManager = new BleModule();
const Bleconnect = BleConnection.getInstance();
const App = observer(() => {
    const { t } = useTranslation();
    const handleAppStateChange = (nextAppState: any) => {
        if (nextAppState != null && nextAppState === 'active') {
            if (Platform.OS === 'ios') {
                CHECKIOSTRACKINGPERMISSION();
            }
        } else if (nextAppState != null && nextAppState === 'background') {
        }
    };

    // 查询本地语言
    const checkLocal = async () => {
        try {
            const LocalLanguage = await RNLocalize.getLocales();
            let language = await Storage.getItem(RecordKeys.language);
            if (!language) {
                language = LocalLanguage[0]?.languageCode == 'zh' ? 'zh' : 'en';
            } else if (LocalLanguage[0]?.languageCode !== language) {
                language = language ? language : 'zh';
            } else {
                language = language ? language : 'zh';
            }
            appStore.switchLanguage(language);
        } catch (error) {
            appStore.switchLanguage('en');
        }
    };

    const devicesMap = useRef(new Map()); // 存储扫描到的设备
    function getDeviceImage(devices: any, device_code: string) {
        const item = devices.find((d: any) => d.firmware_code === device_code);
        return item ? item.device_image : '';
    }
    const handleDiscoverPeripheral = (data) => {
        if (!data.rssi || !data.advertising) return;

        let _bytes;
        if (Platform.OS === 'android') {
            _bytes = data.advertising.manufacturerData?.bytes;
        } else if (Platform.OS === 'ios' && data.advertising.manufacturerData) {
            _bytes = data.advertising.manufacturerData.bytes;
        }
        if (!_bytes) return;

        let deviceSN = qrCode.resolvingBroadcastInformation(_bytes); // 解析设备编码
        if (!deviceSN) return;
        // 假如搜索到了dfuTag
        if (data.name && data.name === 'DfuTarg') {
            const prefix = deviceSN.substring(0, 2);
            const findDevice = modelDevices.find((device) => device.movement === prefix);
            const dfuDevice = {
                id: data.id,
                device_code: data?.name,
                device_sn: deviceSN,
                ...findDevice,
            };
            deviceStore.signDfuDevice(dfuDevice);
            Bleconnect.stopScan();
        }
        const deviceTypeList = deviceStore.device.deviceTypeList || []; // 获取设备类型
        const isDevice = deviceTypeList.some((item) => data.advertising.localName?.includes(item.firmware_code));
        if (!isDevice) return;
        // 设备信息
        let item = {
            device_sn: deviceSN.toUpperCase(),
            id: data.id,
            siginal: data.rssi,
            device_code: data.advertising.localName,
            isCicle: 1,
            device_name: '',
            prevName: deviceSN.substring(13),
            rssi: data.rssi,
            device_image: getDeviceImage(deviceTypeList, data.advertising.localName),
            firmware_code: '',
        };
        // 设备分类
        const device_name = data.advertising.localName;
        if (
            device_name.includes('HA05') ||
            device_name.includes('HA06') ||
            device_name.includes('HA08') ||
            device_name.includes('HA03')
        ) {
            item.isCicle = 1;
            item.device_name = t('watch');
        } else if (device_name.includes('YY01') || device_name.includes('YY08')) {
            item.isCicle = 2;
            item.device_name = t('oneCall');
        } else {
            item.isCicle = 0;
            item.device_name = t('watch1');
        }
        // 存入 Map，避免重复遍历
        devicesMap.current.set(deviceSN, item);
        throttledUpdate(Array.from(devicesMap.current.values()));
    };
    const throttledUpdate = useRef(
        throttle((devices) => {
            deviceStore.serachDevice(devices);
        }, 1000), // 每1秒最多更新一次
    ).current;
    const handleConnectPeripheral = (res) => {
        deviceStore.device.connectedDeviceStatus = 1;
        Bleconnect.stopScan();
    };
    const handleDisconnectPeripheral = () => {
        // serachDevice = [];
        deviceStore.cleanStatus();
    };
    const handleUpdateValue = (data) => {
        BluetoothManager.receiveData(cmd, data.value, (_0bj) => {
            switch (_0bj.cmd) {
                case cmd.kGXYL_setWIFI:
                    deviceStore.updateSuccessWifi(parseInt(_0bj.body.state));
                    break;
                default:
                    break;
            }
        });
    };

    useEffect(() => {
        setTimeout(() => {
            BootSplash.hide();
        }, 200);
        Appearance.setColorScheme('light');
        AppState.addEventListener('change', handleAppStateChange); // ios隐私跟踪权限获取
        checkLocal();

        // 蓝牙模块
        BluetoothManager.start();
        const BleManagerDidUpdateState = BluetoothManager.addListener('BleManagerDidUpdateState', (res) => {
            deviceStore.bleManagerDidUpdateState(res.state);
        }); //蓝牙状态改变的回调
        const BleManagerDiscoverPeripheral = BluetoothManager.addListener(
            'BleManagerDiscoverPeripheral',
            handleDiscoverPeripheral,
        ); //发现设备的回调
        const BleManagerConnectPeripheral = BluetoothManager.addListener(
            'BleManagerConnectPeripheral',
            handleConnectPeripheral,
        ); //连接成功的回调
        const disconnectPeripheralListener = BluetoothManager.addListener(
            'BleManagerDisconnectPeripheral',
            handleDisconnectPeripheral,
        ); //断开连接的回调
        const updateValueListener = BluetoothManager.addListener(
            'BleManagerDidUpdateValueForCharacteristic',
            handleUpdateValue,
        ); //蓝牙数据的回调
        const stopScanHandler = BluetoothManager.addListener('BleManagerStopScan', () => {});
        return () => {
            BleManagerDidUpdateState.remove();
            BleManagerDiscoverPeripheral.remove();
            BleManagerConnectPeripheral.remove();
            disconnectPeripheralListener.remove();
            updateValueListener.remove();
            stopScanHandler.remove();
        };
    }, []);

    return (
        <GestureHandlerRootView>
            <StatusBar backgroundColor={'#fff'} translucent barStyle={'dark-content'} />
            <AppRouter />
            <AgreementModal />
            <Toast ref={(ref) => (global.Toast = ref)} />
            <BannerNotification ref={(ref) => (global.Notice = ref)} />
            <CallNoticeModal />
        </GestureHandlerRootView>
    );
});

export default App;
